/*
 *  Copyright 2008 Danny Lagrouw
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package org.bastion.db4o.service;

import java.util.List;
import java.util.Map;

import org.bastion.query.Matcher;
import org.bastion.service.FindService;
import org.bastion.service.QueryService;
import org.bastion.service.RegisterService;

import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Predicate;

public class Db4oService implements RegisterService, FindService, QueryService {

    private ObjectContainer db;

	public Db4oService(ObjectContainer db) {
		super();
		this.db = db;
	}

	public Long register(Object object) {
        db.set(object);
        return getId(object);
	}

	@SuppressWarnings("unchecked")
	public <T> T find(Class<T> clazz, Object key) {
//      ObjectSet<DomainObject> objects = db.query(new Predicate<DomainObject>() {
//      private static final long serialVersionUID = 1L;
//
//      @Override
//      public boolean match(DomainObject object) {
//          return object.getId().equals(id);
//      }});
//  return objects.isEmpty() ? null : objects.get(0);
        return (T) db.ext().getByID((Long) key);
	}

	public <T> List<T> executeQuery(Class<T> clazz) {
		ObjectSet<T> objects = db.query(new Predicate<T>() {
			private static final long serialVersionUID = 1L;
			
			@Override
			public boolean match(T object) {
				return true;
			}
		});
		return objects;
	}

	protected Long getId(Object object) {
        return db.ext().getID(object);
	}

	public <T> List<T> executeQuery(Class<T> clazz, final Matcher<T> matcher) {
		ObjectSet<T> objects = db.query(new Predicate<T>() {
			private static final long serialVersionUID = 1L;
			
			public boolean match(T object) {
				return matcher.match(object);
			}
		});
		return objects;
	}

	public <T> List<T> executeQuery(Class<T> clazz, String queryName,
			Map<String, Object> parameters) {
		throw new UnsupportedOperationException();
	}

	public boolean prefersNamedQueries() {
		return false;
	}

	public boolean prefersPredicateQueries() {
		return true;
	}

	public boolean supportsNamedQueries() {
		return false;
	}

	public boolean supportsPredicateQueries() {
		return true;
	}

}
